/**
 * 多模态AI交互服务
 * 集成图像识别、语音处理、图像生成和对话优化功能
 */

import apiClient from '@/utils/request';

// 图像识别结果接口
export interface ImageRecognitionResult {
  objects: Array<{
    name: string;
    confidence: number;
    bbox: [number, number, number, number]; // [x, y, width, height]
    category: string;
  }>;
  scene: {
    description: string;
    confidence: number;
    tags: string[];
  };
  text?: Array<{
    text: string;
    confidence: number;
    bbox: [number, number, number, number];
  }>;
  faces?: Array<{
    age_range: [number, number];
    gender: string;
    emotion: string;
    confidence: number;
    bbox: [number, number, number, number];
  }>;
}

// 语音处理结果接口
export interface SpeechProcessingResult {
  transcript: string;
  confidence: number;
  language: string;
  duration: number;
  segments?: Array<{
    text: string;
    start_time: number;
    end_time: number;
    confidence: number;
  }>;
}

// 语音合成参数接口
export interface TextToSpeechParams {
  text: string;
  voice: string; // 'female' | 'male' | 'child'
  speed: number; // 0.5 - 2.0
  pitch: number; // 0.5 - 2.0
  language: string; // 'zh-CN' | 'en-US'
}

// 图像生成参数接口
export interface ImageGenerationParams {
  prompt: string;
  style?: 'realistic' | 'cartoon' | 'sketch' | 'watercolor';
  size?: 'square' | 'portrait' | 'landscape';
  quality?: 'standard' | 'hd';
  count?: number;
}

// 对话上下文接口
export interface ConversationContext {
  user_id: string;
  session_id: string;
  messages: Array<{
    role: 'user' | 'assistant' | 'system';
    content: string;
    timestamp: string;
    metadata?: any;
  }>;
  user_profile?: {
    age_range?: string;
    interests?: string[];
    parenting_stage?: string;
    preferences?: any;
  };
}

// 智能回复结果接口
export interface IntelligentReplyResult {
  reply: string;
  confidence: number;
  intent: string;
  entities: Array<{
    type: string;
    value: string;
    confidence: number;
  }>;
  suggestions?: string[];
  follow_up_questions?: string[];
}

class MultimodalAIService {
  private baseURL = '/api/ai';

  /**
   * 图像识别 - 识别图片中的物体、场景、文字等
   */
  async recognizeImage(imageFile: File | string): Promise<ImageRecognitionResult> {
    try {
      const formData = new FormData();
      
      if (typeof imageFile === 'string') {
        // 如果是URL，直接传递
        formData.append('image_url', imageFile);
      } else {
        // 如果是文件，上传文件
        formData.append('image', imageFile);
      }
      
      const response = await apiClient.post(`${this.baseURL}/image/recognize`, formData, {
        header: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      return response.data;
    } catch (error) {
      console.error('图像识别失败:', error);
      throw new Error('图像识别服务暂时不可用');
    }
  }

  /**
   * 产品识别 - 专门识别母婴产品
   */
  async recognizeProduct(imageFile: File | string): Promise<{
    product_name: string;
    category: string;
    brand?: string;
    confidence: number;
    similar_products: Array<{
      name: string;
      price_range: string;
      rating: number;
      image_url: string;
    }>;
    safety_info?: {
      age_appropriate: string;
      safety_rating: number;
      warnings: string[];
    };
  }> {
    try {
      const formData = new FormData();
      
      if (typeof imageFile === 'string') {
        formData.append('image_url', imageFile);
      } else {
        formData.append('image', imageFile);
      }
      
      const response = await apiClient.post(`${this.baseURL}/image/recognize-product`, formData, {
        header: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      return response.data;
    } catch (error) {
      console.error('产品识别失败:', error);
      throw new Error('产品识别服务暂时不可用');
    }
  }

  /**
   * 症状识别 - 识别宝宝症状相关图片
   */
  async recognizeSymptoms(imageFile: File | string): Promise<{
    possible_conditions: Array<{
      name: string;
      confidence: number;
      severity: 'mild' | 'moderate' | 'severe';
      description: string;
      recommendations: string[];
    }>;
    urgent_care_needed: boolean;
    disclaimer: string;
  }> {
    try {
      const formData = new FormData();
      
      if (typeof imageFile === 'string') {
        formData.append('image_url', imageFile);
      } else {
        formData.append('image', imageFile);
      }
      
      const response = await apiClient.post(`${this.baseURL}/image/recognize-symptoms`, formData, {
        header: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      return response.data;
    } catch (error) {
      console.error('症状识别失败:', error);
      throw new Error('症状识别服务暂时不可用');
    }
  }

  /**
   * 语音转文字
   */
  async speechToText(audioFile: File, language: string = 'zh-CN'): Promise<SpeechProcessingResult> {
    try {
      const formData = new FormData();
      formData.append('audio', audioFile);
      formData.append('language', language);
      
      const response = await apiClient.post(`${this.baseURL}/speech/to-text`, formData, {
        header: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      return response.data;
    } catch (error) {
      console.error('语音转文字失败:', error);
      throw new Error('语音识别服务暂时不可用');
    }
  }

  /**
   * 文字转语音
   */
  async textToSpeech(params: TextToSpeechParams): Promise<{
    audio_url: string;
    duration: number;
    format: string;
  }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/speech/from-text`, params);
      return response.data;
    } catch (error) {
      console.error('文字转语音失败:', error);
      throw new Error('语音合成服务暂时不可用');
    }
  }

  /**
   * 实时语音处理
   */
  async processRealTimeAudio(audioBlob: Blob): Promise<{
    is_speech: boolean;
    transcript?: string;
    confidence?: number;
    intent?: string;
  }> {
    try {
      const formData = new FormData();
      formData.append('audio', audioBlob);
      
      const response = await apiClient.post(`${this.baseURL}/speech/real-time`, formData, {
        header: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      return response.data;
    } catch (error) {
      console.error('实时语音处理失败:', error);
      throw new Error('实时语音处理服务暂时不可用');
    }
  }

  /**
   * AI图像生成
   */
  async generateImage(params: ImageGenerationParams): Promise<{
    images: Array<{
      url: string;
      width: number;
      height: number;
      format: string;
    }>;
    prompt_used: string;
    generation_time: number;
  }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/image/generate`, params);
      return response.data;
    } catch (error) {
      console.error('图像生成失败:', error);
      throw new Error('图像生成服务暂时不可用');
    }
  }

  /**
   * 图像编辑
   */
  async editImage(imageFile: File, editPrompt: string): Promise<{
    edited_image_url: string;
    original_image_url: string;
    edit_description: string;
  }> {
    try {
      const formData = new FormData();
      formData.append('image', imageFile);
      formData.append('edit_prompt', editPrompt);
      
      const response = await apiClient.post(`${this.baseURL}/image/edit`, formData, {
        header: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      return response.data;
    } catch (error) {
      console.error('图像编辑失败:', error);
      throw new Error('图像编辑服务暂时不可用');
    }
  }

  /**
   * 智能对话 - 多轮对话上下文理解
   */
  async intelligentChat(context: ConversationContext, newMessage: string): Promise<IntelligentReplyResult> {
    try {
      const response = await apiClient.post(`${this.baseURL}/chat/intelligent`, {
        context,
        message: newMessage
      });
      
      return response.data;
    } catch (error) {
      console.error('智能对话失败:', error);
      throw new Error('智能对话服务暂时不可用');
    }
  }

  /**
   * 意图识别
   */
  async recognizeIntent(message: string, context?: any): Promise<{
    intent: string;
    confidence: number;
    entities: Array<{
      type: string;
      value: string;
      confidence: number;
    }>;
    suggested_actions: string[];
  }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/nlp/intent`, {
        message,
        context
      });
      
      return response.data;
    } catch (error) {
      console.error('意图识别失败:', error);
      throw new Error('意图识别服务暂时不可用');
    }
  }

  /**
   * 情感分析
   */
  async analyzeSentiment(text: string): Promise<{
    sentiment: 'positive' | 'negative' | 'neutral';
    confidence: number;
    emotions: Array<{
      emotion: string;
      intensity: number;
    }>;
  }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/nlp/sentiment`, {
        text
      });
      
      return response.data;
    } catch (error) {
      console.error('情感分析失败:', error);
      throw new Error('情感分析服务暂时不可用');
    }
  }

  /**
   * 内容摘要生成
   */
  async generateSummary(content: string, maxLength: number = 200): Promise<{
    summary: string;
    key_points: string[];
    original_length: number;
    summary_length: number;
  }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/nlp/summarize`, {
        content,
        max_length: maxLength
      });
      
      return response.data;
    } catch (error) {
      console.error('内容摘要生成失败:', error);
      throw new Error('内容摘要服务暂时不可用');
    }
  }

  /**
   * 多模态内容分析 - 同时分析文字、图片、语音
   */
  async analyzeMultimodalContent(content: {
    text?: string;
    images?: File[];
    audio?: File;
  }): Promise<{
    overall_sentiment: string;
    key_topics: string[];
    content_type: string;
    recommendations: string[];
    safety_check: {
      is_safe: boolean;
      concerns: string[];
    };
  }> {
    try {
      const formData = new FormData();
      
      if (content.text) {
        formData.append('text', content.text);
      }
      
      if (content.images) {
        content.images.forEach((image, index) => {
          formData.append(`image_${index}`, image);
        });
      }
      
      if (content.audio) {
        formData.append('audio', content.audio);
      }
      
      const response = await apiClient.post(`${this.baseURL}/multimodal/analyze`, formData, {
        header: {
          'Content-Type': 'multipart/form-data'
        }
      });
      
      return response.data;
    } catch (error) {
      console.error('多模态内容分析失败:', error);
      throw new Error('多模态分析服务暂时不可用');
    }
  }

  /**
   * 个性化内容生成
   */
  async generatePersonalizedContent(params: {
    user_profile: any;
    content_type: 'article' | 'video_script' | 'social_post' | 'email';
    topic: string;
    tone: 'professional' | 'casual' | 'friendly' | 'educational';
    length: 'short' | 'medium' | 'long';
  }): Promise<{
    content: string;
    title: string;
    tags: string[];
    estimated_reading_time: number;
    seo_keywords: string[];
  }> {
    try {
      const response = await apiClient.post(`${this.baseURL}/content/generate`, params);
      return response.data;
    } catch (error) {
      console.error('个性化内容生成失败:', error);
      throw new Error('内容生成服务暂时不可用');
    }
  }

  /**
   * 获取AI服务状态
   */
  async getServiceStatus(): Promise<{
    services: {
      image_recognition: boolean;
      speech_processing: boolean;
      image_generation: boolean;
      intelligent_chat: boolean;
      nlp_services: boolean;
    };
    response_times: {
      [key: string]: number;
    };
    usage_stats: {
      daily_requests: number;
      monthly_requests: number;
      remaining_quota: number;
    };
  }> {
    try {
      const response = await apiClient.get(`${this.baseURL}/status`);
      return response.data;
    } catch (error) {
      console.error('获取AI服务状态失败:', error);
      throw new Error('无法获取服务状态');
    }
  }
}

// 导出服务实例
export const multimodalAIService = new MultimodalAIService();
export default MultimodalAIService;